package cn.rokhdelar.umbrsapi.management.service;

import cn.rokhdelar.umbrsapi.config.exception.VerifyCaptchaException;
import com.github.benmanes.caffeine.cache.Cache;
import com.wf.captcha.SpecCaptcha;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

@Service
public class CaptchaService {
    private final Cache<String, String> captchaCache;

    public CaptchaService(Cache<String, String> captchaCache) {
        this.captchaCache = captchaCache;
    }

    /**
     * 生成验证码并返回前端
     * @return map
     */
    public Map<String, String> getCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);

        String uuid = UUID.randomUUID().toString();
        String code = specCaptcha.text().toLowerCase();
        captchaCache.put(uuid, code);
        Map<String, String> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("base64", specCaptcha.toBase64());
        return map;
    }

    public Map<String, Object> verifyCaptcha(String uuid, String code) {
        String cacheCode = captchaCache.getIfPresent(uuid);
        Map<String, Object> map = new HashMap<>();
        if(Objects.equals(cacheCode, code.toLowerCase())) {
            map.put("code", Boolean.TRUE);
            map.put("msg", "验证成功。");
            return map;
        } else {
            throw new VerifyCaptchaException("验证码过期或者错误，请刷新验证码再试。");
        }
    }
}
